<template>
  <div class="app-container">

    <el-form :model="form" ref="form" label-width="160px" v-loading="formLoading" :rules="rules">
       <el-form-item label="视频名称：" prop="subCourseName" required>
        <el-input v-model="form.subCourseName"></el-input>
      </el-form-item>
      <el-form-item label="副标题：" prop="subtitle">
        <el-input v-model="form.subtitle"></el-input>
      </el-form-item>
      <el-form-item label="视频详情：" prop="detail">
        <el-input v-model="form.detail"></el-input>
      </el-form-item>
      <el-form-item label="封面上传：" required>
        <el-upload
          class="upload-demo"
          action="http://175.24.33.88:8000/api/admin/course/courseCoverUpload"
          :on-preview="handlePreview"
          ref="upload1"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          multiple
          :auto-upload="true"
          :http-request="cfileUpload"
          :with-credentials="true"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
        <img v-show= imgshow height="414" width="720"  :src="'http://175.24.33.88:8001/static'+this.form.coverPath" />
      </el-form-item>

<!--        <el-form-item label="添加视频:" prop="viedoName">-->
<!--        <el-select-->
<!--          clearable-->
<!--          filterable-->
<!--          remote-->
<!--          reserve-keyword-->
<!--          v-model="form.viedoName"-->
<!--          :remote-method="getvideoName"-->
<!--          @select="handleSelectClass"-->
<!--          :loading="loading"-->
<!--        >-->
<!--          <el-option-->
<!--            v-for="item in videoNameList"-->
<!--            :key="item"-->
<!--            :label="item"-->
<!--            :value="item"-->
<!--          ></el-option>-->
<!--        </el-select>-->
<!--        <el-button @click="addItem" type="text" style="margin-left:20px">新增</el-button>-->
<!--      </el-form-item>-->
        <el-form-item label="添加视频：" prop="videoName">
          <!--filterable添加搜索功能-->
          <el-select v-model="form.videoName" placeholder="添加视频"
          clearable
          filterable
          remote
          reserve-keyword>
            <el-option
            v-for="item in videoNameList"
            :key="item"
            :label="item"
            :value="item"
          ></el-option>
          </el-select>
          <el-button @click="addItem" type="text" icon="el-icon-plus" style="margin-left:20px">新增</el-button>
        </el-form-item>

      <el-form-item label="视频上传：" >
        <el-upload
          class="upload-demo"
          action="http://175.24.33.88:8000/api/admin/subCourse/videoUpload"
          :on-preview="handleviedoPreview"
          ref="upload"
          :on-remove="handlevideoRemove"
          :before-remove="beforeviedoRemove"
          accept=".mp4, .avi, .flv, .mov, .wmv"
          multiple
          :auto-upload="true"
          :http-request="fileUpload"
          :with-credentials="true"
        >
          <el-button size="small" type="primary" >点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传mp4/avi/flv/mov/wmv视频文件，且不超过1024M</div>
        </el-upload>

        <div class="video_playIcon" v-if="!initVideo.play" @click="playVideo"></div>

            <video v-show= videoshow class="video" height="414" width="720" ref="video" :src="initVideo.url" @pause="handPlay(2,2)" @play="handPlay(2,1)"
                  @loadedmetadata="getAudioLength(2)" @timeupdate="videoTimeUpdate" @click="playVideo">
                该浏览器不支持video
            </video>
            <div class="video_control">
                <div class="progress">

            <el-slider  v-show= videoshow class="commonSlider"  :show-tooltip="true" v-model="initVideo.currentTime"
                       :max="initVideo.videoLength" @change="changeVideoTime">
            </el-slider>
            <div class="time" v-show= videoshow>

                <span>{{initVideo.currentTime | videoTime}}</span>
                <span>{{initVideo.videoLength | videoTime}}</span>
            </div>
        </div>
    </div>


      </el-form-item>
      <!--添加讲师包括职称和姓名(有修改)-->
      <el-form-item label="添加讲师:" required>
        <el-form-item label="讲师职称：" prop="lecturerId">
          <el-select v-model="form.lecturerTitle" placeholder="讲师职称" filterable clearable @change="professionalChange">
            <el-option
               v-for="item in lecturertitleList"
              :key="item.id"
              :value="item.id"
              :label="item.titleName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="讲师姓名：" prop="lecturerName">
          <!--filterable添加搜索功能-->
          <el-select v-model="form.lecturerId" placeholder="讲师姓名"
          clearable
          filterable
          remote
          reserve-keyword>
            <el-option
              v-for="item in lecturerNameList"
              :key="item.id"
              :value="item.id"
              :label="item.lecturerName"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>

    </el-form>


  </div>
</template>

<script>
import {selectLecturer,createLecturer,getLecturerPageList} from "@/api/xzs/lecturer";
import {userApi} from "@/api/system/user";
import {selectsubCourse,getViedo,insertViedo,createsubCourse} from "@/api/xzs/subCourse";
import {listUser} from "@/api/category/lecturetitle";
import request from '@/utils/request'
import Editor from '@/components/Editor';
export default {
  inject:['reload'],
   components: {
    Editor
  },
  data() {
    return {
      form: {
        id: null,
        titleName: "",
        pageNum: 1,
        pageSize: 10,
        subCourseName: "",
        subtitle: "",
        detail: "",
        coverPath: "",
        contentPath: "",
        lecturerName: "",
        lecturerTitle: "",
        lecturerId: "",
        videoName:"",
        videoPath:"",
        status: 1
      },
      videoTime:null,
      initVideo: {
                play: false,//播放还是暂停 true播放中
                videoLength: null,//时长
                url: '',//视频课件Url
                currentTime: 0,//当前播放时间
                lastTime: null,//标记时间戳
                name: "",
            },
            //音频
            initAudio: {
                play: false,//播放还是暂停 true播放中
                audioLength: 0,//audio时长
                url: "",//音频课件url
                currentTime: 0,//当前播放时间
                lastTime: null,//标记时间戳
                name: "",
            },

      imgshow:false,
      videoshow:false,
      lecturertitleList:[],
      lecturerNameList:[],
      videoNameList:[],
      formLoading: false,
      rules: {
        subCourseName: [
          { required: true, message: "请输入课程名称", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    let id = this.$route.query.id
    let _this = this
    this.getLecturer();
    this.getlecturerName();
    this.getvideoName();
    if (id && parseInt(id) !== 0) {
      _this.formLoading = true;
      selectsubCourse(id).then(re => {
        this.imgshow=true;
        if(re.response.contentPath=="")
        {
            this.videoshow=false;
        }
        else
        {
            this.videoshow=true;
        }
        _this.form = re.response;
        this.form.videoName=re.response.videoName;
         _this.form.lecturerName = this.$route.query.lecturerName;
         if(this.form.videoName=="")
         {
           this.initVideo.url='http://175.24.33.88:8001/static'+this.form.contentPath
         }
         else
         {
           this.videoshow=false;
           this.initVideo.url=null;
         }
         this.initVideo.videoLength=this.form.videoLength
        _this.formLoading = false;
      });
    }
  },
  methods: {
      getLecturer() {

      this.formLoading=true;
      listUser(this.form)
        .then(res => {
          this.formLoading=false;
          if (res.code == 1) {
            this.lecturertitleList = res.response.list;
            console.log(this.lecturertitleList)

            console.log(this.lecturertitleList.item)
          }
        })
        .catch(res => {
          this.formLoading=false;
        });
    },
    //从接口获取讲师姓名
    getlecturerName() {
      this.formLoading=true;
      getLecturerPageList({ condition: null, professionalTitle: this.form.lecturerTitle,pageNum: 1, pageSize: 100 })
        .then(res=>{
          this.formLoading=false;
          if(res.code==1){
            this.lecturerNameList=res.response.list;
            console.log(this.lecturerNameList)
            // console.log(res.response.list)
          }
        })
        .catch(res=>{
          this.formLoading=false;
        });
      console.log(this.lecturerNameList)
    },
    playVideo() {//播放视频
            if (this.initVideo.play) {
                this.$refs.video.pause();
            } else {
                Math.abs(this.initVideo.currentTime - this.$refs.video.currentTime) > 2 ? this.$refs.video.currentTime = this.initVideo.currentTime : '';
                this.$refs.video.play();
                this.$refs.video.muted = false
            }
        },
        videoTimeUpdate() {//更新视频时间。节流，每秒触发一次
            let nowTime = Date.now()
            let gapTime = 1000;
            if (!this.initVideo.lastTime || nowTime - this.initVideo.lastTime > gapTime) {
                if (this.$refs.video) {
                    let time = this.$refs.video.currentTime;
                    this.initVideo.currentTime = time;
                }
                this.initVideo.lastTime = nowTime
            }
        },
        changeVideoTime(val) {//改变视频时间
            //console.log(val, 'video')
            if (this.$refs.video) {
                this.$refs.video.currentTime = val;
            }
        },
        getAudioLength(type) {//获取音视频时长 1音频 2视频
            if (type == 1) {
                this.initAudio.audioLength = this.$refs.audio.duration
                console.log('获取音频时长', this.$refs.audio.duration)
            }
            if (type == 2) {
                this.initVideo.videoLength = this.$refs.video.duration
                this.videoTime = this.$refs.video.duration
                console.log('获取视频时长', this.$refs.video.duration)
            }
        },
        handPlay(type, status) {//音视频播放暂停 type:1 音频 2视频 status 1播放 2暂停
            if (type == 1) {
                status == 1 ? this.initAudio.play = true : this.initAudio.play = false;
            } else {
                status == 1 ? this.initVideo.play = true : this.initVideo.play = false;
            }
        },


    //职称更改
    professionalChange(id){
      this.getlecturerName()
    },

    remoteMethodClass(queryString) {
      this.loading = true;
      classSysList({
        className: queryString || "",
        pageNum: 1,
        pageSize: 20
      })
        .then(res => {
          this.loading = false;
          if (res.code == 1) {
            this.classList = res.response.list;
          }
        })
        .catch(res => {
          this.loading = false;
        });
    },
    handleSelectClass(id) {},

    getvideoName() {
      this.formLoading=true;
      getViedo(null) .then(res=>{
        this.formLoading=false;
        // if(res.code==405){
        //   this.$message({
        //   showClose: true,
        //   message: "未查询到视频数据"
        // });
        // }Invalid prop: type check failed for prop "max". Expected Number with value NaN, got String with value "0:0:4".
        // else
        if(res.code==1){
          this.videoNameList=res.response;
        }
      })
      .catch(res=>{
        this.formLoading=false;
      });
    },
        //添加新记录
    addItem() {
      this.formLoading=true;
      if (!this.form.videoName) {
        this.$message({
          showClose: true,
          message: "请先选择视频名称"
        });
        this.formLoading=false;
      } else {
        //console.log(this.videoPageList)
        insertViedo({videoName:this.form.videoName}) .then(res=>{
        if(res.code==1){
          if(this.form.contentPath==""||null)
          {
            this.form.videoPath=res.response.videoPath;
            this.form.videoLength=res.response.videoLength;
            this.$message.success(res.message);
            this.formLoading=false;

          }
          else
          {
            this.$message({
            showClose: true,
            message: "已上传视频，不可重复选择!"
            });
            this.form.videoName="";
            this.formLoading=false;
          }

        }
      })
      .catch(res=>{
        this.formLoading=false;
      });
      }
    },

    fileUpload(file){
      let files = file.file
      console.log(file.file)
      let formObj = new FormData();
      formObj.append("uploadFile", files)
      request({
        method: "post",
        url: "/api/admin/subCourse/videoUpload", // 请求地址
        data: formObj, // 参数
        //responseType: "blob", // 表明返回服务器返回的数据类型
        headers: {
          "Content-Type": "application/json"
        }
      }).then(res => {
      //form('/api/admin/subCourse/videoUpload',formObj)
        //console.log(res);
        this.form.contentPath = res.response.videoPath;
        this.form.videoLength = res.response.videoLength;
        this.initVideo.url='http://175.24.33.88:8001/static'+this.form.contentPath
        this.initVideo.videoLength=this.form.videoLength
        this.videoshow=true;
      })
    },
    cfileUpload(file){
      let files = file.file
      console.log(file.file)
      let formObj = new FormData();
      formObj.append("uploadFile", files)
       request({
        method: "post",
        url: "/api/admin/course/courseCoverUpload", // 请求地址
        data: formObj, // 参数
        //responseType: "blob", // 表明返回服务器返回的数据类型
        headers: {
          "Content-Type": "application/json"
        }
      }).then(res => {
        console.log(res);
        this.form.coverPath = res.response;
        this.imgshow=true;
      })
    },
    submitForm() {
      let _this = this;
      this.$refs.form.validate(valid => {
        if (valid) {
          this.formLoading = true;
          if(this.form.contentPath=="")
          {
            if(this.form.videoName=="")
            {
                this.$message({
                showClose: true,
                message: "未上传视频!"
                });
                this.formLoading=false;
            }
            else
            {
              this.form.contentPath=this.form.videoPath;
                 createsubCourse(this.form)
                  .then(data => {
                    if (data.code === 1) {
                      _this.$message.success(data.message);
                      _this.$router.push("/courses/videos/index");
                    } else {
                      _this.$message.error(data.message);
                      _this.formLoading = false;
                    }
                  })
                  .catch(e => {
                    _this.formLoading = false;
                  });
            }
          }
          else
          {
            if(this.form.videoName!="")
            {
                this.$message({
                showClose: true,
                message: "已上传视频，不可重复选择!"
                });
                this.formLoading=false;
            }
            else
            {
                 createsubCourse(this.form)
                  .then(data => {
                    if (data.code === 1) {
                      _this.$message.success(data.message);
                      _this.$router.push("/courses/videos/index");
                    } else {
                      _this.$message.error(data.message);
                      _this.formLoading = false;
                    }
                  })
                  .catch(e => {
                    _this.formLoading = false;
                  });
            }
          }

        } else {
          return false;
        }
      });
    },

     //视频
    handlevideoRemove(file,uploadFile) {
      this.videoshow=false;
      this.form.contentPath="" ;
      this.initVideo.url="";
    },
    handleviedoPreview(file) {
      //console.log(file);
    },
    beforeviedoRemove(file) {
      return this.$confirm(`确定移除?`);
    },
    //上传照片方法
    handleRemove(file,uploadFile) {
      this.form.coverPath=null;
      this.imgshow=false;
    },
    handlePreview(file) {
      console.log(file);
    },
    //handleExceed(files, fileList) {
      //this.$message.warning(
        //`当前限制选择3个文件，本次选择了${
          //files.length
        //}个文件，共选择了${files.length + fileList.length}个文件`
     // );
    //},
    beforeRemove(file) {
      return this.$confirm(`确定移除?`);
    },
    resetForm () {
      this.reload()
    }
  }
};
</script>
